#!/usr/bin/env python
import sys
import os
import re
import lxml.etree


class PlatformProjectUpdater:

    def __init__(self):
        self.local_props = self.load_props("local.properties")
        self.project_props = self.load_props("project.properties")
        self.platform_path = "../../android-platform-headers"

    @staticmethod
    def load_props(fname):
        d = {}
        for l in open(fname):
            l = l.strip()
            if not l or l[0] == "#":
                continue
            k, v = [a.strip() for a in l.split("=", 1)]
            d[k] = v
        return d

    @staticmethod
    def load_mk(fname):
        d = {}
        for l in open(fname):
            l = l.strip()
            if not l or l[0] == "#":
                continue
            try:
                k, v = [a.strip() for a in re.split("[:+]=", l, 1)]
                d[k] = v
            except:
                pass
        return d

    def symlink_lib(self, lib, core=False):
        if core:
            p = "corelibs"
        else:
            p = "libs"
        if not os.path.isdir(p):
            os.mkdir(p)
        p = p + "/" + lib + ".jar"
        if os.path.islink(p):
            os.remove(p)
        src = "%s/%s/javalib/%s.jar" % (self.platform_path, self.project_props["target"], lib)
        os.symlink(src, p)
        print "Symlinked " + p


    @staticmethod
    def get_sdk_build_xml():
        sdk_build_xml = None
        tree = lxml.etree.parse("build.xml")
        for t in tree.xpath("import"):
            if "${sdk.dir}" in t.get("file"):
                return t.get("file")

    def process(self):
        sdk_build_xml = self.get_sdk_build_xml()
        sdk_build_xml = sdk_build_xml.replace("${sdk.dir}", self.local_props["sdk.dir"])
        tree = lxml.etree.parse(sdk_build_xml)

        root = lxml.etree.Element("project")
        root.append(lxml.etree.fromstring("""
        <path id="framework.complete">
            <pathelement path="corelibs/core.jar" />
            <pathelement path="corelibs/ext.jar" />
            <pathelement path="corelibs/framework.jar" />
        </path>
        """))

        target = tree.xpath("target[@name='-compile']")[0]
        javac = target.xpath("//javac")[0]
        javac.set("bootclasspathref", "framework.complete")

        root.append(target)
        with open("custom_rules.xml", "w") as f:
            f.write(lxml.etree.tostring(root, pretty_print=True))
        print "Added custom_rules.xml"

        self.symlink_lib("core", True)
        self.symlink_lib("ext", True)
        self.symlink_lib("framework", True)

        mk = self.load_mk("Android.mk")
        for lib in mk.get("LOCAL_STATIC_JAVA_LIBRARIES", "").split():
            self.symlink_lib(lib)


def main():
    p = PlatformProjectUpdater()
    p.process()


if __name__ == "__main__":
    main()
